import { onMounted, onBeforeUnmount, ref } from "vue";

export interface UseKeyboardOptions {
  onOpen?: (keyboardHeight: number) => void;
  onClose?: () => void;
  threshold?: number;
}

function getViewportHeight(): number {
  if (typeof window === "undefined") return 0;
  const vv = (window as any).visualViewport as VisualViewport | undefined;
  if (vv && typeof vv.height === "number") return vv.height;
  return window.innerHeight || document.documentElement.clientHeight || 0;
}

export function useKeyboard(options: UseKeyboardOptions = {}) {
  const { onOpen, onClose, threshold = 100 } = options;

  const isOpen = ref(false);
  const keyboardHeight = ref(0);
  let baselineHeight = 0;

  function handleResize() {
    const current = getViewportHeight();
    if (baselineHeight === 0) {
      baselineHeight = current;
      return;
    }

    const delta = baselineHeight - current;

    if (delta > threshold) {
      if (!isOpen.value) {
        isOpen.value = true;
      }
      keyboardHeight.value = delta;
      onOpen && onOpen(keyboardHeight.value);
    } else {
      if (isOpen.value) {
        isOpen.value = false;
        keyboardHeight.value = 0;
        onClose && onClose();
      }
      // When keyboard closes, update baseline upward to the latest max height
      if (current > baselineHeight) baselineHeight = current;
    }
  }

  onMounted(() => {
    baselineHeight = getViewportHeight();
    const vv = (window as any).visualViewport as VisualViewport | undefined;
    if (vv) {
      vv.addEventListener("resize", handleResize);
      // Some Android devices also change on scroll during keyboard
      vv.addEventListener("scroll", handleResize);
    } else {
      window.addEventListener("resize", handleResize);
    }
  });

  onBeforeUnmount(() => {
    const vv = (window as any).visualViewport as VisualViewport | undefined;
    if (vv) {
      vv.removeEventListener("resize", handleResize);
      vv.removeEventListener("scroll", handleResize);
    } else {
      window.removeEventListener("resize", handleResize);
    }
  });

  return { isOpen, keyboardHeight };
}


